package com.sita.tboard.ui.fragment;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.sita.bike.R;
import com.sita.bike.event.UpdateProfileEvent;
import com.sita.bike.support.GlobalContext;
import com.sita.bike.utils.AccountUtils;
import com.sita.bike.utils.BitmapUtils;

import app.akexorcist.bluetotohspp.library.BluetoothSPP;
import app.akexorcist.bluetotohspp.library.BluetoothState;
import app.akexorcist.bluetotohspp.library.DeviceList;
import de.greenrobot.event.EventBus;

//import com.jeremyfeinstein.slidingmenu.lib.app.SlidingFragmentActivity;

public class DeviceMineFragment extends Fragment {

    public static SharedPreferences BluetoothSharedPreferences;
    private static DeviceMineFragment fragment;
    public ImageView img_slide_menu;
    public RelativeLayout mLayout;
    public SharedPreferences.Editor editor;
    private BluetoothSPP bt;
    private ImageButton btnBluetooth;
    private ImageView img_Icon;
    private TextView tvName, tv_link;
    private String userName;

    public static DeviceMineFragment getInstance() {
        if (fragment == null) {
            synchronized (DeviceMineFragment.class) {
                if (fragment == null) {
                    fragment = new DeviceMineFragment();
                }
            }

        }
        return fragment;
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_device_mine, null);
        initView(view);
        initBluetooth();
        return view;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        EventBus.getDefault().register(this);
        super.onActivityCreated(savedInstanceState);
    }

    @Override
    public void onDestroy() {
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
        super.onDestroy();
    }

    @Override
    public void onStart() {
        startBlueToothService();
        autoConnectBluetooth();
        super.onStart();
    }

    public void initView(View view) {
        tv_link = (TextView) view.findViewById(R.id.tv_link);
        mLayout = (RelativeLayout) view.findViewById(R.id.title_bar_layout);
        mLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN);
        img_slide_menu = (ImageView) view.findViewById(R.id.img_slide_menu);
//        img_slide_menu.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                SlidingFragmentActivity s = (SlidingFragmentActivity) getActivity();
//                s.getSlidingMenu().toggle();
//            }
//        });
        btnBluetooth = (ImageButton) view.findViewById(R.id.img_turn_off);
        img_Icon = (ImageView) view.findViewById(R.id.img_Icon);

        tvName = (TextView) view.findViewById(R.id.tv_name);

        AccountUtils.SetHeaderName(img_Icon, tvName, getActivity());
    }


    private void initBluetooth() {
        BluetoothSharedPreferences = getActivity().getSharedPreferences("test", Activity.MODE_PRIVATE);
        editor = BluetoothSharedPreferences.edit();

        bt = GlobalContext.getBluetoothSPP();

        if (!bt.isBluetoothAvailable()) {
            Toast.makeText(getActivity().getApplicationContext()
                    , "蓝牙不可用"
                    , Toast.LENGTH_SHORT).show();
            getActivity().finish();
        }

        bt.setBluetoothConnectionListener(new BluetoothSPP.BluetoothConnectionListener() {
            public void onDeviceConnected(String name, String address) {
                Toast.makeText(getActivity().getApplicationContext()
                        , "蓝牙已连接" + name + "\n" + address
                        , Toast.LENGTH_SHORT).show();
//              //蓝牙连接成功后保存本次的连接设备信息
                tv_link.setText("已连接");
                editor.putString("name", name);
                editor.putString("address", address);
                editor.commit();

                //实现跳转
//                getActivity().findViewById(R.id.rb_dashboard).performClick();
                RelativeLayout rb_dashboard = (RelativeLayout) getActivity().findViewById(R.id.layout_dashboard);
                rb_dashboard.performClick();
//                  rb_dashboard.setSelected(true);
            }

            public void onDeviceDisconnected() {
                Toast.makeText(getActivity().getApplicationContext()
                        , "蓝牙已断开", Toast.LENGTH_SHORT).show();
                tv_link.setText("未连接");
//                btnBluetooth.setVisibility(View.VISIBLE);
            }

            public void onDeviceConnectionFailed() {
                Toast.makeText(getActivity().getApplicationContext()
                        , "蓝牙连接失败", Toast.LENGTH_SHORT).show();
//                btnBluetooth.setVisibility(View.VISIBLE);
            }
        });


        btnBluetooth.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (bt.getServiceState() == BluetoothState.STATE_CONNECTED) {
                    bt.disconnect();
                } else {
                    Intent intent = new Intent(getActivity(), DeviceList.class);
                    getActivity().startActivityForResult(intent, BluetoothState.REQUEST_CONNECT_DEVICE);
                }
            }
        });
    }

    public BluetoothSPP getBt() {
        return bt;
    }

    private void autoConnectBluetooth() {
        String address = BluetoothSharedPreferences.getString("address", "onetime");
//        Toast.makeText(getActivity().getApplicationContext(), address, Toast.LENGTH_SHORT).show();
        if (address != "onetime") {
            bt.connect(address);
        }
    }

    private void startBlueToothService() {
        if (!bt.isBluetoothEnabled()) {
            Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(intent, BluetoothState.REQUEST_ENABLE_BT);
        } else {
            if (!bt.isServiceAvailable()) {
                bt.setupService();
                //bt.startService(BluetoothState.DEVICE_ANDROID);
                bt.startService(BluetoothState.DEVICE_OTHER);
//                setup();
            }
        }
    }

    public void handleActivityResult(int requestCode, int resultCode, Intent data) {
        if (data != null) {
            String address = data.getExtras().getString(BluetoothState.EXTRA_DEVICE_ADDRESS);
            if (requestCode == BluetoothState.REQUEST_CONNECT_DEVICE) {
                if (resultCode == Activity.RESULT_OK)
                    bt.connect(data);
            } else if (requestCode == BluetoothState.REQUEST_ENABLE_BT) {
                if (resultCode == Activity.RESULT_OK) {
                    bt.setupService();
//                bt.startService(BluetoothState.DEVICE_ANDROID);
                    bt.startService(BluetoothState.DEVICE_OTHER);
//                setup();
                } else {
                    Toast.makeText(getActivity().getApplicationContext()
                            , "蓝牙------失败"
                            , Toast.LENGTH_SHORT).show();
                    getActivity().finish();
                }
            }
        }
    }

    public void getHeaderImageAndName() {
        Drawable drawable = AccountUtils.getAccountHeader(getActivity());
        if (drawable == null) {
            drawable = AccountUtils.getDefaultAccountHeader(getActivity());
        }
        img_Icon.setImageDrawable(drawable);
        userName = AccountUtils.getUserDisplayName();
        tvName.setText(userName);
    }

    public void onEvent(UpdateProfileEvent event) {
        if (event.headImg != null) {
            img_Icon.setImageBitmap(BitmapUtils.bytesToBitmap(event.headImg));
        }

        if (!TextUtils.isEmpty(event.nickName)) {
            tvName.setText(event.nickName);
        }
    }
}
